<template>
  <el-form ref="deptForm" label-width="120px" :model="form" :rules="rules">
    <el-form-item label="部门名称" prop="name">
      <el-input
        v-model="form.name"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input
        v-model="form.code"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width: 80%" placeholder="请选择">
        <el-option
          v-for="item in Employees"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input
        v-model="form.introduce"
        style="width: 80%"
        placeholder="1-300个字符"
        type="textarea"
        :rows="3"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="$emit('close')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments, getDepartmentsDetail, updateDepartments } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
      console.log(value, 'value')
      console.log(this.originList, 'this.originList')
      let existCodeList = this.originList.map(item => item.code)
      console.log(existCodeList, 'existCodeList')
      // 编辑的状态 先移除自己的编码
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.id)
      }
      if (existCodeList.includes(value)) {
        // 存在 抛出错误
        callback(new Error(`部门编码:${value}已存在`))
      } else {
        // 放行
        callback()
      }
      callback()
    }
    const validName = (rule, value, callback) => {
      console.log(value, 'value')
      console.log(this.originList, 'this.originList')
      let existNameList = this.originList.map(item => item.code)
      console.log(existNameList, 'existCodeList')
      if (this.isEdit) {
        // 在所有的部门中找到当前的部门数据对象
        const curDepartment = this.originList.find(item => item.id === this.id)
        const pid = curDepartment
        // 所有的兄弟部门的pid是一样的
        const brothers = this.originList.filter(item => item.id === pid)
        // 排除自己
        existNameList = brothers.filter(item => item.id !== this.id).map(item => item.name)
      }
      console.log(existNameList)
      // 编辑的状态 先移除自己的编码
      if (existNameList.includes(value)) {
        // 存在 抛出错误
        callback(new Error(`部门名称:${value}已存在`))
      } else {
        // 放行
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }

        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      },
      Employees: []
    }
  },
  watch: {
    // 解决数据不更新的方法3 使用watch监听id的变化
    'id': function(newVal, oldVal) {
      console.log(newVal, oldVal)
      this.loadDepartmentsDetail()
    }
  },
  created() {
    this.loadEmployeeSimple()
    this.loadDepartmentsDetail()
  },
  methods: {
    // 获取员工列表信息
    async loadEmployeeSimple() {
      try {
        const res = await getEmployeeSimple()
        console.log(res, '员工列表')
        if (res.code === 10000) {
          this.Employees = res.data
        }
      } catch (error) {
        this.$message.error(error)
      }
    },
    hSubmit() {
      // this.hAdd()
      // 兜底检验
      // 实现部门新增
      this.$refs.deptForm.validate(valid => {
        if (!valid) return // 检验失败
        this.isEdit ? this.doEdit() : this.hAdd()
      })
    },
    async hAdd() {
      // console.log(id)
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.$emit('success')
      } catch (error) {
        console.log(error)
        this.$message.error(error)
      }
    },
    async loadDepartmentsDetail() {
      // 是编辑的情况下，要去获取详情 把数据回显
      if (this.isEdit) {
        try {
          const res = await getDepartmentsDetail(this.id)
          console.log(res, 'getDepartmentsDetail')
          this.form = res.data
        } catch (error) {
          console.log(error)
        }
      }
    },
    // 编辑部门
    async doEdit() {
      try {
        const res = await updateDepartments(this.form)
        console.log(res, 'updateDepartments')
        if (res.code !== 10000) return this.$message.error(res.error)
        this.$message.success(res.message)
        // 重新渲染
        // 子传父
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    resetForm() {
      // 重置表单的检验规则和数据
      this.$refs.deptForm.resetFields()
    }
  }
}
</script>
